package com.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {

	private static final int BSIZE = 1024;

	public static void main(String[] args) throws IOException {
		// 写文件
		// getChannel产生FileChannel
		FileChannel fc = new FileOutputStream("c:/z.txt").getChannel();
		// wrap将已经存在的字节数组包装成ByteBuffer，称之为数组支持的ByteBuffer
		fc.write(ByteBuffer.wrap("some text".getBytes()));
		fc.close();

		// 末尾追加内容
		fc = new RandomAccessFile("c:/z.txt", "rw").getChannel();
		// 挪到文件的最后
		fc.position(fc.size());
		fc.write(ByteBuffer.wrap("add text".getBytes()));
		fc.close();

		// 读文件
		fc = new FileInputStream("c:/z.txt").getChannel();
		// 使用allocate方法分配ByteBuffer
		ByteBuffer buff = ByteBuffer.allocate(BSIZE);
		// 一旦调用read来告知FileChannel向ByteBuffer存储字节，就必须调用缓冲器上的flip()
		fc.read(buff);
		buff.flip();
		while (buff.hasRemaining()) {
			System.out.print((char) buff.get());
		}
	}

}
